package ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.impl;

import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.DtoManager;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.DtoManagerConstructArgs;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.DtoManagerFactory;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.manager.spring.DtoManagerSpringFactory;
import ace.cmp.spring.util.core.SpringUtils;
import org.springframework.beans.factory.ObjectProvider;

/**
 * .
 * @author caspar
 */
public class DtoManagerSpringFactoryImpl implements DtoManagerSpringFactory {

  private final DtoManagerFactory managerFactory;
  private final SpringUtils springUtils;

  public DtoManagerSpringFactoryImpl(DtoManagerFactory managerFactory, SpringUtils springUtils) {
    this.managerFactory = managerFactory;
    this.springUtils = springUtils;
  }

  @Override
  public <EntityT, IdT, EntityDtoT> DtoManager<EntityT, IdT, EntityDtoT> getOrCreate(DtoManagerConstructArgs<EntityT, IdT, EntityDtoT> args) {

    ObjectProvider<DtoManager<EntityT, IdT, EntityDtoT>> objectProvider = springUtils.getBeanByClassWithGenericsObjectProvider(
        DtoManager.class,
        args.getEntityClass(),
        args.getIdClass(),
        args.getEntityDtoClass()
    );

    return objectProvider.getIfAvailable(() -> this.managerFactory.getOrCreate(args));
  }
}
